package shili;

import org.apache.log4j.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

// 示例8(2)
public class IntermediaryInvocationHandler implements InvocationHandler {
    private Logger logger = Logger.getLogger(IntermediaryInvocationHandler.class);
    /**
     * 被代理的目标对象
     * @param proxy the proxy instance that the method was invoked on
     *
     * @param method the {@code Method} instance corresponding to
     * the interface method invoked on the proxy instance.  The declaring
     * class of the {@code Method} object will be the interface that
     * the method was declared in, which may be a superinterface of the
     * proxy interface that the proxy class inherits the method through.
     *
     * @param args an array of objects containing the values of the
     * arguments passed in the method invocation on the proxy instance,
     * or {@code null} if interface method takes no arguments.
     * Arguments of primitive types are wrapped in instances of the
     * appropriate primitive wrapper class, such as
     * {@code java.lang.Integer} or {@code java.lang.Boolean}.
     *
     * @return
     * @throws Throwable
     */
    private Object target;
    public void setTarget(Object target){
        this.target = target;
    }

    /**
     * 为被代理的接口方法定义的代理业务规则
     * @param proxy the proxy instance that the method was invoked on
     *
     * @param method the {@code Method} instance corresponding to
     * the interface method invoked on the proxy instance.  The declaring
     * class of the {@code Method} object will be the interface that
     * the method was declared in, which may be a superinterface of the
     * proxy interface that the proxy class inherits the method through.
     *
     * @param args an array of objects containing the values of the
     * arguments passed in the method invocation on the proxy instance,
     * or {@code null} if interface method takes no arguments.
     * Arguments of primitive types are wrapped in instances of the
     * appropriate primitive wrapper class, such as
     * {@code java.lang.Integer} or {@code java.lang.Boolean}.
     *
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object feedback = method.invoke(target,args);   // 反射执行目标对象的实际业务
        after();
        return "看房记录: 买家反馈 “" + feedback + "“";
    }
    public void before(){
        logger.debug("前期准备.");
        logger.debug("查找房源.");
        logger.debug("和卖家沟通时间.");
    }
    public void after(){
        logger.debug("后期跟踪.");
        logger.debug("和买家共同意见.");
    }
}
